<template>
  <div class="dashboard-container" :class="{ 'dark-mode': isDarkMode }">
    <header class="dashboard-header">
      <div class="logo-container">
        <h1 class="title" style="font-size: 60px;">环境监测数据中心</h1>
        <div class="time-display">{{ currentTime }}</div>
      </div>
      <div class="header-controls">
        <el-switch v-model="isDarkMode" active-text="暗色模式" inactive-text="亮色模式" inline-prompt />
        <el-button type="primary" @click="refreshAllData">刷新数据</el-button>
      </div>
    </header>

    <div class="dashboard-content">
      <div class="dashboard-row">
        <div class="dashboard-card overview-stats">
          <h3>环境监测概览</h3>
          <div class="stats-grid">
            <div v-for="(stat, index) in overviewStats" :key="index" class="stat-item" :class="stat.status">
              <div class="stat-value">{{ stat.value }}{{ stat.unit }}</div>
              <div class="stat-label">{{ stat.label }}</div>
              <div class="stat-trend">
                <el-icon v-if="stat.trend > 0">
                  <ArrowUp />
                </el-icon>
                <el-icon v-else-if="stat.trend < 0">
                  <ArrowDown />
                </el-icon>
                <span>{{ Math.abs(stat.trend) }}%</span>
              </div>
            </div>
          </div>
        </div>

        <div class="dashboard-card">
          <h3>空气质量指数 (AQI)</h3>
          <air-quality-chart :chart-data="airQualityData" />
        </div>
      </div>

      <div class="dashboard-row">
        <div class="dashboard-card">
          <h3>区域污染物排名</h3>
          <div class="card-header-actions">
            <el-radio-group v-model="pollutantType" size="small">
              <el-radio-button value="pm25">PM2.5</el-radio-button>
              <el-radio-button value="pm10">PM10</el-radio-button>
              <el-radio-button value="no2">NO₂</el-radio-button>
            </el-radio-group>
          </div>
          <pollution-ranking-chart :chart-data="pollutionRankingData" :pollutant-type="pollutantType" />
        </div>

        <div class="dashboard-card">
          <h3>温湿度趋势</h3>
          <temperature-humidity-chart :chart-data="temperatureHumidityData" />
        </div>
      </div>

      <div class="dashboard-row">
        <div class="dashboard-card">
          <h3>水质监测指标</h3>
          <water-quality-chart :chart-data="waterQualityData" />
        </div>

        <div class="dashboard-card">
          <h3>能源消耗分析</h3>
          <energy-consumption-chart :chart-data="energyConsumptionData" />
        </div>
      </div>

      <div class="dashboard-row">
        <div class="dashboard-card full-width">
          <h3>环境监测站点分布</h3>
          <monitoring-stations-map :map-data="monitoringStationsData" />
        </div>
      </div>
    </div>

    <el-dialog v-model="alarmVisible" title="环境预警" width="30%">
      <div class="alarm-content">
        <el-alert :title="currentAlarm.title" :description="currentAlarm.description" :type="currentAlarm.type"
          show-icon />
        <p class="alarm-time">预警时间: {{ currentAlarm.time }}</p>
        <p class="alarm-location">预警地点: {{ currentAlarm.location }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="alarmVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleAlarmAction">处理预警</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount } from 'vue';
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue';
import AirQualityChart from './components/AirQualityChart.vue';
import PollutionRankingChart from './components/PollutionRankingChart.vue';
import TemperatureHumidityChart from './components/TemperatureHumidityChart.vue';
import WaterQualityChart from './components/WaterQualityChart.vue';
import EnergyConsumptionChart from './components/EnergyConsumptionChart.vue';
import MonitoringStationsMap from './components/MonitoringStationsMap.vue';

// 状态变量
const isDarkMode = ref(false);
const currentTime = ref('');
const pollutantType = ref('pm25');
const alarmVisible = ref(false);
const currentAlarm = ref({});

// 数据变量
const airQualityData = ref([]);
const pollutionRankingData = ref([]);
const temperatureHumidityData = ref([]);
const waterQualityData = ref([]);
const energyConsumptionData = ref([]);
const monitoringStationsData = ref([]);
const overviewStats = ref([
  { label: '空气质量指数', value: 75, unit: '', trend: 5, status: 'warning' },
  { label: '平均温度', value: 24.5, unit: '°C', trend: -2, status: 'normal' },
  { label: '平均湿度', value: 65, unit: '%', trend: 3, status: 'normal' },
  { label: '水质指数', value: 92, unit: '', trend: 1, status: 'good' },
  { label: '噪声水平', value: 58, unit: 'dB', trend: -4, status: 'normal' },
  { label: '能源消耗', value: 1250, unit: 'kWh', trend: -7, status: 'good' },
]);

// WebSocket连接
let ws = null;

// 更新时间
const updateTime = () => {
  const now = new Date();
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
};

// 初始化WebSocket
const initWebSocket = () => {
  ws = new WebSocket('ws://localhost:3000/ws');

  ws.onopen = () => {
    console.log('WebSocket连接已建立');
    ws.send(JSON.stringify({ type: 'subscribe', channels: ['environment_data'] }));
  };

  ws.onmessage = (event) => {
    const data = JSON.parse(event.data);

    switch (data.type) {
      case 'air_quality':
        airQualityData.value = data.data;
        break;
      case 'pollution_ranking':
        pollutionRankingData.value = data.data;
        break;
      case 'temperature_humidity':
        temperatureHumidityData.value = data.data;
        break;
      case 'water_quality':
        waterQualityData.value = data.data;
        break;
      case 'energy_consumption':
        energyConsumptionData.value = data.data;
        break;
      case 'monitoring_stations':
        monitoringStationsData.value = data.data;
        break;
      case 'overview_stats':
        overviewStats.value = data.data;
        break;
      case 'alarm':
        currentAlarm.value = data.data;
        alarmVisible.value = true;
        break;
    }
  };

  ws.onclose = () => {
    console.log('WebSocket连接已关闭');
    // 尝试重新连接
    setTimeout(initWebSocket, 5000);
  };

  ws.onerror = (error) => {
    console.error('WebSocket错误:', error);
  };
};

// 刷新所有数据
const refreshAllData = () => {
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: 'refresh_all' }));
  }
};

// 处理预警
const handleAlarmAction = () => {
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({
      type: 'alarm_handled',
      id: currentAlarm.value.id
    }));
  }
  alarmVisible.value = false;
};

// 初始化数据
const fetchInitialData = async () => {
  try {
    const response = await fetch('http://localhost:3000/api/initial-data');
    const data = await response.json();

    airQualityData.value = data.airQuality;
    pollutionRankingData.value = data.pollutionRanking;
    temperatureHumidityData.value = data.temperatureHumidity;
    waterQualityData.value = data.waterQuality;
    energyConsumptionData.value = data.energyConsumption;
    monitoringStationsData.value = data.monitoringStations;
    overviewStats.value = data.overviewStats;
  } catch (error) {
    console.error('获取初始数据失败:', error);
  }
};

// 生命周期钩子
onMounted(() => {
  updateTime();
  const timeInterval = setInterval(updateTime, 1000);
  fetchInitialData();
  initWebSocket();

  onBeforeUnmount(() => {
    clearInterval(timeInterval);
    if (ws) {
      ws.close();
    }
  });
});
</script>

<style>
:root {
  --primary-color: #1890ff;
  --success-color: #52c41a;
  --warning-color: #faad14;
  --danger-color: #f5222d;
  --bg-color: #f0f2f5;
  --card-bg: #ffffff;
  --text-color: #333333;
  --border-color: #e8e8e8;
}

.dark-mode {
  --primary-color: #177ddc;
  --success-color: #49aa19;
  --warning-color: #d89614;
  --danger-color: #d32029;
  --bg-color: #141414;
  --card-bg: #1f1f1f;
  --text-color: #f0f0f0;
  --border-color: #303030;
}

.dashboard-container {
  min-height: 100vh;
  background-color: var(--bg-color);
  color: var(--text-color);
  transition: all 0.3s;
  padding: 20px;
}

.dashboard-header {
  flex-direction: column;
  /* 改为垂直布局 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--border-color);
  position: relative;
  /* 确保子元素可以使用绝对定位 */
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  /* 水平居中 */
  justify-content: center;
  /* 垂直居中 */
}

.title {
  font-size: 28px;
  margin: 0;
  color: var(--primary-color);
  /* 回退样式 */
  background: linear-gradient(45deg, var(--primary-color), #36cfc9);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.time-display {
  font-size: 14px;
  color: var(--text-color);
  opacity: 0.8;
  margin-top: 5px;
}

.header-controls {
  display: flex;
  gap: 15px;
  align-items: center;
  position: absolute;
  /* 绝对定位 */
  right: 20px;
  /* 距离屏幕右边缘 20px */
  top: 50%;
  /* 垂直居中 */
  transform: translateY(-50%);
  /* 修正垂直居中偏移 */
}

.dashboard-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.dashboard-row {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.dashboard-card {
  flex: 1;
  min-width: 300px;
  background-color: var(--card-bg);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 16px;
  position: relative;
  transition: all 0.3s;
}

.dashboard-card:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.2);
  transform: translateY(-2px);
}

.dashboard-card h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: 500;
  color: var(--text-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header-actions {
  position: absolute;
  right: 16px;
  top: 16px;
}

.full-width {
  flex-basis: 100%;
}

.overview-stats {
  background: linear-gradient(135deg, var(--card-bg), var(--card-bg) 60%, rgba(24, 144, 255, 0.1));
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.stat-item {
  padding: 16px;
  border-radius: 8px;
  background-color: rgba(0, 0, 0, 0.02);
  border: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  transition: all 0.3s;
}

.stat-item:hover {
  transform: scale(1.02);
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: var(--text-color);
  opacity: 0.8;
}

.stat-trend {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
}

.good {
  border-left: 3px solid var(--success-color);
}

.warning {
  border-left: 3px solid var(--warning-color);
}

.danger {
  border-left: 3px solid var(--danger-color);
}

.normal {
  border-left: 3px solid var(--primary-color);
}

.alarm-content {
  margin-bottom: 20px;
}

.alarm-time,
.alarm-location {
  margin: 10px 0;
  font-size: 14px;
}

@media (max-width: 768px) {
  .dashboard-row {
    flex-direction: column;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>